<?php
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-5-26
 * Time: 上午9:25
 */

namespace PFT;
use PDO;
use WeChat\Api\Api;

class SaleList {

    private $db;
    private $aid;
    private $fid;

    public function __construct(PDO $db, $aid = 0, $fid = 0)
    {
        $this->db   = $db;
        $this->aid  = $aid;
        $this->fid  = $fid;
    }

    public function getTotal(Array $param, $array_search='')
    {
        $where = "1=1";
        $where_arr = array();
        foreach ($param as $col=>$val) {
            $where .= " AND e.`$col`=?";
            $where_arr[] = $val;
        }
        $lid_list = array();
        //自己供应的产品
        $sql_get_mysql = <<<SQL
SELECT DISTINCT p.contact_id FROM uu_products p
WHERE apply_did=? AND p.p_status=0 AND p.apply_limit=1
SQL;
        $stmt_self = $this->db->prepare($sql_get_mysql);
        $stmt_self->execute(array($this->fid));
        while($id = $stmt_self->fetch(PDO::FETCH_COLUMN)) {
            $lid_list[] = $id;
        }
//        print_r($lid_list);
//        exit;
//        $lid_list = $stmt_self->fetchAll(PDO::FETCH_COLUMN);

        $get_total  = <<<SQL
SELECT DISTINCT p.contact_id from pft_p_apply_evolute e
LEFT JOIN uu_products p ON p.id=e.pid WHERE $where
 AND p.p_status=0 AND p.apply_limit=1
SQL;
//        echo $get_total;
        $stmt       = $this->db->prepare($get_total);
        $stmt->execute($where_arr);
        while($id = $stmt->fetch(PDO::FETCH_COLUMN)) {
            $lid_list[] = $id;
        }
//        $lid_other  = $stmt->fetchAll(PDO::FETCH_COLUMN);
        return array_unique($lid_list);
    }

    /**
     *查询会员可分销产品信息.
     *@param $lid 景区id，默认不传，传入只返回改景区产品
     *@return array 会员可分销产品，含直接供应和转供应产品
     */
    public function salePros(Array $param, $lid_arr, $offset=0, $size=10){
        if (empty($param) || count($param)==0) {
            throw new \Exception('参数错误');
        }
        $where = "1=1";
        $where_arr = array();
        foreach ($param as $col=>$val) {
            $where .= " AND `$col`=?";
            $where_arr[] = $val;
        }
        if (!$lid_arr) {
            return array();
//            return Api::EMPTY_CONTENT;
        }
        $lid_str = implode(',', $lid_arr);
        $pid_list = $data = array();
        //获取自己供应的产品
        $sql_self_pid = <<<SQL
        SELECT id as pid,contact_id as lid,apply_did as sid FROM uu_products
        WHERE apply_did={$this->fid} AND contact_id IN($lid_str) AND p_status=0
        AND apply_limit=1
SQL;
//        echo $sql_self_pid;
        $stmt_self = $this->db->prepare($sql_self_pid);
        $stmt_self->execute();
        while($row = $stmt_self->fetch(PDO::FETCH_ASSOC)) {
            $pid_list[] = $row['pid'];
            $data[]     = $row;
        }
        //获取可销售产品ID
        $sql_sale_pid = <<<SQL
        SELECT pid,sid,lid FROM pft_p_apply_evolute WHERE fid=? AND lid IN($lid_str)
SQL;

//        echo $sql_sale_pid;
//        exit;
        $stmt = $this->db->prepare($sql_sale_pid);
        $stmt->execute(array($this->fid));
        while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
//            print_r($row);
            $pid_list[] = $row['pid'];
            $data[]     = $row;
        }
//        print_r($pid_list);
//        exit;
//        print_r($pid_list);
//        print_r($data);
//        exit;
//        $output = array();
//        array_walk($data, function($val, $key) use(&$output){
//            if ($val>1) $output[] = $key;
//        }) ;


        $pid_str = implode(',', array_unique($pid_list));

        //获取产品信息
        $sql_tpl = <<<SQL
SELECT p.id as pid,p.contact_id,p.apply_did,p.p_status,t.id as tid,t.pay,
t.getaddr,t.title,t.tprice,t.notes,t.buy_limit_low,t.status,t.order_end,
t.order_start,t.delaytype FROM uu_products p
LEFT JOIN uu_jq_ticket t ON p.id=t.pid
WHERE p.id IN($pid_str) AND p.p_status=0 AND p.apply_limit=1
SQL;
//        echo $sql_tpl;
        $stmt = $this->db->prepare($sql_tpl);
        $stmt->execute();
        $sale_list = array();
        while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
            $sale_list[$row['pid']] = $row;
        }
//        print_r($sale_list);
//        exit;
        $output = array();
        foreach ($data as $r) {
            if (!$sale_list[$r['pid']]) continue;
            $output[$r['lid']][] = array_merge($r, $sale_list[$r['pid']]);
        }
        return $output;
    }

    /**
     * 获取已经开启转供应的产品
     *
     * @param $fid
     * @param $aid
     * @return array
     */
    public function getExistPid($fid, $aid)
    {
        //检测产品是否已经开启转供应
        $sql_chk_evo = <<<SQL
SELECT pid FROM pft_p_apply_evolute WHERE fid=$fid AND sid=$aid AND lvl=1
SQL;
//        echo $sql_chk_evo,PHP_EOL;
        $stmt = $this->db->prepare($sql_chk_evo);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    /**
     * 添加分销产品
     *
     * @param $pid
     * @param $lid
     * @param int $aid
     * @param int $fid
     * @return int
     */
    public function AddEvolute($pid, $lid, $aid,$fid )
    {
        $aid = !$aid ? $aid : $this->aid;
        $fid = !$fid ? $fid : $this->fid;
        $str = 'INSERT INTO pft_p_apply_evolute(fid,sid,sourceid,pid,lid,lvl,aids,rectime) VALUES';
        $str_val = '';
        if (is_array($pid)) {
            foreach ($pid as $id) {
                $str_val .= "($fid,$aid,$aid,$id,{$lid[$id]},1,$aid,now()),";
            }
            $str_val = rtrim($str_val, ',');
        } else {
            $str_val .= "($fid,$aid,$aid,$pid,$lid,1,$aid,now())";
        }
//        echo $str_val;
//        exit;
        return $this->db->exec( $str . $str_val );
    }

    /**
     * 更新分销产品状态0可分销1禁止分销
     *
     * @param int $pid 产品ID
     * @param int $status 默认禁止分销
     * @param int $aid
     * @param int $fid
     * @return int
     */
    public function UpdateEvoluteStatus($pid, $status=1, $aid,$fid)
    {
        $aid = !$aid ? $aid : $this->aid;
        $fid = !$fid ? $fid : $this->fid;
        $str = "UPDATE pft_p_apply_evolute SET `status`=$status";
        $where = " fid=$fid AND sid=$aid AND lvl=1 AND pid";
        if (is_array($pid)) {
            $where .= ' IN ('.implode(',', $pid).') LIMIT ' . count($pid);
        } else {
            $where .= " =$pid LIMIT 1";
        }
        return $this->db->exec( $str . $where );
    }
    protected function getPidLid($aid=0)
    {
        if ($aid) $where = " WHERE apply_did=$aid";
        $sql_pid = "SELECT id,contact_id as lid FROM uu_products $where";
        $stmt = $this->db->prepare($sql_pid);
        $stmt->execute();
        $pid_lid_list = array();
        while($tmp=$stmt->fetch(PDO::FETCH_ASSOC)) {
            $pid_lid_list[$tmp['id']] = $tmp['lid'];
        }
        return $pid_lid_list;
    }
    public function data_move($aid=3614,$fid=94)
    {
//        if (!$aid) {
//            $sql = "SELECT aid FROM pft_product_sale_list where fid=$fid";
//        }
        $pid_lid_list = $this->getPidLid($aid);

//        var_export($pid_list);
//        exit;
        $sql = "select pids,aid from pft_product_sale_list where fid=$fid AND pids<>''";
        if ($aid>0) {
            $sql .= " AND aid=$aid";
        }
//        echo $sql;
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $total = 0;
        $str_val  = '';
//        print_r($data);
//        exit;
        foreach ($data as $row) {
            if ($row['pids']=='A') {
                $all_list[] = $row['aid'];
            } else {
                $pid_arr[$row['aid']] = explode(',', $row['pids']);
            }
        }
//        print_r($all_list);
//        print_r($pid_arr);
//        exit;

        $pid_exist_list = $this->getExistPid($fid, $aid);

//        print_r($pid_exist_list);
//        exit;
        $str = 'INSERT INTO pft_p_apply_evolute(fid,sid,sourceid,pid,lid,lvl,aids,rectime) VALUES';
        //等于A的产品处理
        if (count($all_list)) {
            $apply_did = implode(',', $all_list);
            $sql_all = "SELECT id,apply_did FROM uu_products WHERE apply_did IN(".$apply_did.")";
            $stmt = $this->db->prepare($sql_all);
            $stmt->execute();
            while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
                //过滤已经开启转分销的产品id
                if (in_array($row['id'], $pid_exist_list)) {
                    echo 'pass1 ' . $row['id'] . PHP_EOL;
                    continue;
                }
                $str_val .= "($fid,{$row['apply_did']},{$row['apply_did']},{$row['id']},{$pid_lid_list[$row['id']]},1,{$row['apply_did']},now()),";
            }
        }
//        echo $str_val;
//        exit;
        if (count($pid_arr)) {
            foreach($pid_arr as $aid=>$pid_list) {
                foreach ($pid_list as $pid) {
                    //过滤已经开启转分销的产品id
                    if (in_array($pid, $pid_exist_list)) {
                        echo 'pass2 ' . $pid . PHP_EOL;
                        continue;
                    }
                    $str_val .= "($fid,$aid,$aid,$pid,{$pid_lid_list[$pid]},1,$aid,now()),";
                    $total += 1;
                }
            }
        }

        $str_val = $str . rtrim($str_val,',');
//        echo $str_val;
//        exit;
        if ($ret = $this->db->exec($str_val)!==false) {
            echo 'Success',$ret;
        }
//        echo $str . $str_val;
//        exit;
//        $sql_2 = "SELECT pid,sid FROM pft_p_apply_evolute WHERE fid=4";
//        $stmt = $this->db->prepare($sql_2);
//        $stmt->execute();
//        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
//        foreach ($data as $row) {
//            $total += 1;
//            $pid_arr[$row['sid']] = $row['pid'];
//        }
    }

    public function update_lid($fid)
    {
        $sql = "SELECT pid FROM pft_p_apply_evolute WHERE fid=$fid AND lid=0";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $pid_list = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $pid_lid_list = $this->getPidLid();
//        print_r($pid_list);
//        exit;
//        print_r($pid_lid_list);
        foreach ($pid_list as $pid) {

            $sql_lid = "UPDATE pft_p_apply_evolute SET lid={$pid_lid_list[$pid]} WHERE pid=$pid AND lid=0";
            $this->db->exec($sql_lid);
            echo $sql_lid .'<br/>'. PHP_EOL;
        }
    }

}